import 'dart:async';

import 'package:common_utils/common_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter_chubao/config/app_manger_user.dart';
import 'package:flutter_chubao/models/model_user.dart';
import 'package:flutter_chubao/tools/app_tool_toast.dart';
import 'package:flutter_chubao/tools/tool_app/app_dio_client.dart';
import 'package:flutter_chubao/tools/tool_app/app_dio_response.dart';
import 'package:get/get.dart';

import 'app_login_state.dart';

/// @description:
/// @author
/// @date: 2023-12-13 13:54:00
class AppLoginLogic extends GetxController {
  final state = AppLoginState();
  bool checkPhone() {
    if (state.isAgree == false) {
      AppToolToast.showToast('请阅读并同意协议');
      return false;
    } else if (!RegexUtil.isMobileSimple(state.phoneController.text)) {
      AppToolToast.showToast('请输入正确的账号');
      return false;
    } else if (state.codeController.text.length < 6) {
      AppToolToast.showToast('请输入至少六位密码');
      return false;
    } else {
      return true;
    }
  }

  sendSms() async {
    if (state.isAgree == false) {
      AppToolToast.showToast('请阅读并同意协议');
      return;
    }
    AppDioResponse response = await AppDioClient.post('SSApis.smsSend', data: {
      'mobile': state.phoneController.text,
    });
    if (response.ok) {
      if (state.timerUtil == null) {
        state.millisUntilFinished = 60;
        state.timerUtil = Timer.periodic(const Duration(seconds: 1), (timer) {
          state.millisUntilFinished--;
          if (state.millisUntilFinished <= 0) {
            state.timerUtil?.cancel();
            state.timerUtil = null;
          }
          update(['millisUntilFinished']);
        });
        update(['millisUntilFinished']);
      }
    }
  }

  clickLogin() async {
    if (checkPhone()) {
      AppToolToast.showLoading();
      AppDioResponse response = await AppDioClient.post('/mini/chubao/login',
          data: {
            'account': state.phoneController.text,
            'pass': state.codeController.text
          });
      AppToolToast.dismiss();
      if (response.ok) {
        AppDioClient.appToken = response.data['token'];
        getUserInfo(response.data['token']);
      }
    }
  }

  getUserInfo(String token) async {
    AppDioClient.appToken = token;
    UserEntity? userInfoEntity = await AppManagerUser.getPostUserInfo();

    if (userInfoEntity != null) {
      userInfoEntity.token = token;
      AppManagerUser.userLogin(userInfoEntity);
    } else {
      AppDioClient.appToken = '';
    }
  }

  @override
  void onInit() {
    super.onInit();
    if (kDebugMode) {
      state.codeController.text = '123123';
      state.phoneController.text = '18982026766';
    }
  }
}
